<template>
    <div>
        <form action="/">
            <van-search v-model.trim="keywords" show-action background="#3296fa" placeholder="请输入搜索关键词"
                @search="onSearch" @cancel="onCancel" @focus="isShowResult=false" />
        </form>
        <!-- 历史，建议，结果 -->
        <component :is="componentName" :keywords="keywords" @updata-keywords="onSearch"></component>
    </div>
</template>

<script>
import SearchHistory from '@/components/SearchHistory'
import SearchResult from '@/components/SearchResult'
import SearchSuggestions from '@/components/SearchSuggestions'
import { mapState, mapMutations } from 'vuex'
export default {
    data() {
        return {
            keywords: '',
            isShowResult: false
        }
    },
    components: {
        SearchHistory,
        SearchResult,
        SearchSuggestions
    },
    computed: {
        ...mapState(['histories']),
        componentName() {
            //没有实际内容渲染SearchHistory
            if (this.keywords === '') {
                return 'SearchHistory'
            }
            //有值
            if (this.isShowResult) {
                return 'SearchResult'
            }
            return 'SearchSuggestions'
        }
    },
    methods: {
        ...mapMutations(['SET_HISTORY']),
        onSearch(val) {
            this.keywords = val
            let newHistory = [...this.keywords, ...this.histories]
            newHistory = [...new Set(newHistory)]
            this.SET_HISTORY(newHistory)
            this.isShowResult = true
        },
        onCancel() {
            // if (this.keywords === '') {
            //     window.history.go(-1)
            // } else {
            //     this.keywords = ''
            // }
        }
    }
}
</script>

<style lang="less" scoped>
.van-search {
    .van-search__action {
        color: #fff;
    }
}
</style>